package com.study.service.impl;

import com.study.constant.Constants;
import com.study.netty2.ChannelMap;
import com.study.service.ChannelService;
import com.study.service.RedisService;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author mjy
 * @date 2021/12/08
 * @description
 */
@Service
public class ChannelServiceImpl implements ChannelService {


    @Autowired
    private RedisService redisService;

    @Override
    public void setDeviceOnlineAndRefreshChannle(String deviceCard, Channel channel) {
        //存储管道
        Channel channelOld = ChannelMap.get(deviceCard);
        if (channelOld == null) {
            ChannelMap.add(deviceCard, channel);
        } else {
            if (!channelOld.equals(channel)) {//如果通道发生变化
                ChannelMap.removerByKey(deviceCard);
                ChannelMap.add(deviceCard, channel);
            }
        }
        //存储redis
        setDeviceOnline(deviceCard);
    }

    @Override
    public void setDeviceOnline(String deviceCard) {
        //存储redis
        redisService.setKey(Constants.DEVICE_ONLINE_PREFIX + deviceCard, Constants.DEVICE_ONLINE, Constants.READER_IDLE_TIME, TimeUnit.SECONDS);
    }

    @Override
    public void removeDeviceOnline(String deviceCard) {
        redisService.deleteKey(Constants.DEVICE_ONLINE_PREFIX+deviceCard);
    }

    @Override
    public void removerDeviceOnLineAndChannel(String deviceCard) {
        ChannelMap.removerByKey(deviceCard);
        removeDeviceOnline(deviceCard);
    }

    @Override
    public void closeChannel(Channel channel) {
        String key = ChannelMap.getKey(channel);
        removerDeviceOnLineAndChannel(key);
    }


}
